const moment = require('moment');
const superagent = require('superagent');
const { Op } = require('sequelize');
let TEST = false;
// TEST = true;

module.exports = function (app, opts) {
  const synchronizePepReserveProject = app.fs.scheduleInit(
    {
      interval: '0 0 0 * * *', //每天0点执行
      immediate: false,
      // proRun: !TEST,
    },
    async () => {
      try {
        const { models } = app.fs.dc;
        let loginUrl =opts.loginUrl +'/_api/login';
        //pm鉴权路由
        let initUrl = opts.loginUrl+'/_api/init';
        let projectUserInfo = opts.projectUserInfo;
        let firstProjectsUrl = opts.firstProjectsUrl;
        let secondProjectsUrl = opts.secondProjectsUrl;
        let loginName = projectUserInfo.split('/')[0];
        let loginPwd = projectUserInfo.split('/')[1];

        let loginData = {
          username: loginName,
          password: loginPwd,
          code: 'PEP',
          clientIp: null,
        };

        // 检查是否是第一次运行
        const isFirstRun = !(await models.Project.findOne({
          where: { pep_id: { [Op.ne]: null } },
        }));
        console.log('isFirstRun:', isFirstRun);

        // 发起登录请求
        const loginResponse = await superagent.post(loginUrl, loginData);
        //额外需要访问一个接口才能获取改接口的数据
        if (loginResponse.status === 200) {
          console.log('登录成功');
          const token = loginResponse.body.token;
          let sendData = {
            dataRange: {
              OA: false,
              PM: false,
            },
            department: loginResponse.body.department,
            userRes: {
              id: loginResponse.body.id,
              companyId: loginResponse.body.companyId,
            },
          };
          const authData = await superagent.post(
            `${initUrl}/sys/PM/dataRange`,
            sendData
          ).query({ token })
          if(!authData.body.PM){
            return
          }
          // 获取项目数据
          const apiReserveProjects = await superagent.get(firstProjectsUrl).query({ token });
          console.log('apiReserveProjects:', apiReserveProjects.body);

          const apiReserveIndividualProjects = await superagent
            .get(secondProjectsUrl)
            .query({ token });
          console.log('apiReserveIndividualProjects:', apiReserveIndividualProjects.body);

          let projects = [];
          if (
            apiReserveProjects.body.rows.length > 0 &&
            apiReserveIndividualProjects.body.rows.length > 0
          ) {
            const project_reserve = apiReserveProjects.body.rows.map((project) => ({
              name: project.name,
              userId: 1,
              pepId: project.id,
              createTime: project.createTime,
            }));
            const project_reserve_individual = apiReserveIndividualProjects.body.rows.map(
              (project) => ({
                name: project.name,
                userId: 1,
                pepId: project.id,
                createTime: project.createTime,
              })
            );
            projects = [...project_reserve, ...project_reserve_individual];
            console.log('projects:', projects);
          } else {
            console.log('没有数据');
          }

          if (isFirstRun) {
            await models.Project.bulkCreate(projects);
            console.log('项目数据已全部插入数据库');
          } else {
            async function updateProject() {
              const yesterday = moment().subtract(1, 'day').startOf('day');
              console.log('yesterday:', yesterday);
              const projectsToUpdate = projects.filter((project) =>
                moment(project.createTime).isSameOrAfter(yesterday)
              );
              console.log('projectsToUpdate:', projectsToUpdate);

              for (const project of projectsToUpdate) {
                const [record, created] = await models.Project.findOrCreate({
                  where: { pepId: project.pepId },
                  defaults: {
                    name: project.name,
                    userId: project.userId,
                    pepId: project.pepId,
                    createTime: project.createTime,
                  },
                });
                if (!created) {
                  console.log(`项目${project.pepId}已存在，不进行插入`);
                } else {
                  console.log(`项目${project.pepId}已插入`);
                }
              }
              console.log('前一天创建的项目数据已更新');
            }
            updateProject().catch((err) => {
              console.error('更新数据失败', err);
            });
          }
        } else {
          console.log('登录失败');
        }
      } catch (error) {
        console.error('Error in synchronizePepReserveProject:', error);
        app.fs.logger.error(`schedule: synchronizePepReserveProject, error: ${error}`);
      }
    }
  );

  return {
    synchronizePepReserveProject,
  };
};
